﻿using System;
using System.Linq.Expressions;
using System.Windows.Forms;
using Loki.Utils;

namespace Loki.UI.Win
{
    public abstract class Binder : LokiObject
    {
        public IValueConverter GlyphConverter { get; set; }

        public IValueConverter NameConverter { get; set; }

        protected IConductor GetContainer<TModel>(Control control, Expression<Func<TModel, object>> propertyGetter) where TModel : class
        {
            TModel model = View.GetViewModel<TModel>(control);

            if (model == null)
            {
                Log.WarnFormat("Form {0} is not binded to a {1} model", control, model);
                return null;
            }

            var bindingTarget = propertyGetter.Compile()(model) as IConductor;

            var containerModel = bindingTarget as IConductor;
            if (containerModel == null)
            {
                Log.Warn("Navigation/Menu model must be a container");
                return null;
            }
            else
            {
                return containerModel;
            }
        }

        protected string GetName(object item)
        {
            var display = item as IHaveDisplayName;
            if (display != null)
            {
                if (NameConverter == null)
                {
                    return display.DisplayName;
                }
                else
                {
                    return NameConverter.Convert(display.DisplayName, typeof(string), null, UIContext.Windows.Culture).SafeToString();
                }
            }
            else
            {
                return string.Empty;
            }
        }
    }
}